package com.theoryinpractice.hudson.core;

import com.intellij.openapi.diagnostic.Logger;
import com.theoryinpractice.hudson.model.Build;
import com.theoryinpractice.hudson.model.Job;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import javax.swing.tree.DefaultMutableTreeNode;
import java.io.IOException;
import java.net.URL;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: amrk
 * Date: May 20, 2007
 * Time: 8:17:55 PM
 * To change this template use File | Settings | File Templates.
 */
public class HudsonBuilder {
    private static final Logger LOGGER = Logger.getInstance("Hudson");

    public DefaultMutableTreeNode buildHudsonTreeNode(String basepath) {

        DefaultMutableTreeNode serversNode = new DefaultMutableTreeNode(basepath);

        SAXBuilder builder = new SAXBuilder();
        builder.setValidation(false);
        try {
            URL url = new URL(basepath + "/api/xml");
            LOGGER.info("Loading jobs from " + url.toString());
            Document doc = builder.build(url);

            List<Element> jobElements = doc.getRootElement().getChildren("job");
            for (Element jobElement : jobElements) {

                Job job = new Job(
                        jobElement.getChildText("name"),
                        jobElement.getChildText("color"),
                        jobElement.getChildText("url")
                );

                DefaultMutableTreeNode jobNode = new DefaultMutableTreeNode(job);

                Document jobDoc = builder.build(new URL(job.getUrl() + "api/xml"));
                Element jobDetailNode = jobDoc.getRootElement();

                Build firstBuild = makeBuildFromElement(jobDetailNode.getChild("firstBuild"));
                Build lastSuccessfulBuild = makeBuildFromElement(jobDetailNode.getChild("lastSuccessfulBuild"));
                Build lastFailedBuild = makeBuildFromElement(jobDetailNode.getChild("lastFailedBuild"));
                Build lastBuild = makeBuildFromElement(jobDetailNode.getChild("lastBuild"));

                if (firstBuild != null) jobNode.add(new DefaultMutableTreeNode(firstBuild));
                if (lastBuild != null) jobNode.add(new DefaultMutableTreeNode(lastBuild));
                if (lastFailedBuild != null) jobNode.add(new DefaultMutableTreeNode(lastFailedBuild));
                if (lastSuccessfulBuild != null) jobNode.add(new DefaultMutableTreeNode(lastSuccessfulBuild));

                serversNode.add(jobNode);
            }

        } catch (JDOMException e) {
            // TODO Throw custom HudsonException
            LOGGER.error(e.getMessage(), e);
        } catch (java.net.ConnectException e) {
            // TODO Throw custom HudsonException
            LOGGER.warn(e.getMessage(), e);
        } catch (IOException e) {
            // TODO Throw custom HudsonException
            LOGGER.error(e.getMessage(), e);
        }

        return serversNode;

    }

    private Build makeBuildFromElement(Element element) {

        if (element != null) {
            Build build = new Build();
            build.setType(element.getName());
            build.setBuildNumber(Integer.parseInt(element.getChildText("number")));
            build.setUrl(element.getChildText("url"));

            return build;
        } else {
            return null;
        }
    }

}
